package cn.fzkj.gulimall.service.impl;

import cn.fzkj.common.to.es.SkuEsModel;
import cn.fzkj.gulimall.config.EsConfig;
import cn.fzkj.gulimall.constant.EsConstant;
import cn.fzkj.gulimall.service.ProductService;
import com.alibaba.fastjson.JSONObject;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;

/**
 * @DESCRIPTION
 * @Author yaya
 * @DATE 2022/5/14
 */
@Service
public class ProductSeriveImpl implements ProductService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public boolean productsUp(List<SkuEsModel> skuEsModelList) throws IOException {
        // 1、给es创建索引 product, 映射关系

        if (CollectionUtils.isEmpty(skuEsModelList)){
            return true;
        }
        // 2、保存数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel model : skuEsModelList) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(model.getSkuId() + "");
            String jsonString = JSONObject.toJSONString(model);
            indexRequest.source(jsonString, XContentType.JSON);

            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = client.bulk(bulkRequest, EsConfig.COMMON_OPTIONS);
        return !bulk.hasFailures();
    }
}
